package com.ytc.mybatis.config;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;

import com.ytc.web.interceptor.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyBatisPlusConfig {


   //忽略的表名称
   private static String [] tables = new String[]{"tb_dictionary","tb_category",
           "undo_log","tb_application","tb_company","tb_resource","tb_role_resource","tb_user_role"};

   //注册mybatis的插件
   @Bean
   public MybatisPlusInterceptor mybatisPlusInterceptor() {
      MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

      //多租户插件
      //注册多租户插件
      interceptor.addInnerInterceptor(tenantLineInnerInterceptor());
      //分页的插件
      interceptor.addInnerInterceptor(paginationInnerInterceptor());
      return interceptor;
   }

   //分页的插件配置
   @Bean
   public PaginationInnerInterceptor paginationInnerInterceptor() {
      return new PaginationInnerInterceptor(DbType.MYSQL);
   }

   /**
    * 多租户的插件配置
    *    eg：select * from table
    *    1、拦截执行的SQL语句
    *    2、根据插件的配置，查看此表（table）是否需要添加额外的机构id
    *    3、如果需要添加机构id，改造SQL  : select * from table  WHERE 租户字段（company_id） = 数据
    */
   @Bean
   public TenantLineInnerInterceptor tenantLineInnerInterceptor() {
      return new TenantLineInnerInterceptor(new TenantLineHandler() {

         //设置租户数据
         public Expression getTenantId() {
            Long companyId = AuthInfoHolder.getCompanyId();
            if(companyId == null) {
               return null;
            }else {
               return new LongValue(companyId);
            }
         }

         //多租户的租户id字段
         public String getTenantIdColumn(){
            return "company_id";
         }

         //设置表是否需要进行多租户配置  true忽略，false-拼接
         public boolean ignoreTable(String tableName) {
            if(ArrayUtil.contains(tables,tableName)) { //忽略的表数组中，是否包含当前数据库表
               return true;
            }
            //为了防止代码异常
            Expression id = getTenantId();
            if(id == null) {
               return true;
            }
            return false;
         }
      });
   }
}